<?php
/**
 * Created by IntelliJ IDEA.
 * User: luwei
 * Date: 2017/7/5
 * Time: 16:00
 */

namespace app\modules\api\models;


use app\models\AgentGood;
use app\models\Banner;
use app\models\Cat;
use app\models\Goods;
use app\models\HomeBlock;
use app\models\HomeNav;
use app\models\LiveIndex;
use app\models\LiveStream;
use app\models\MiaoshaGoods;
use app\models\Option;
use app\models\PtGoods;
use app\models\PtOrder;
use app\models\PtOrderDetail;
use app\models\Store;
use app\models\Topic;
use app\models\Attr;
use app\models\AttrGroup;
use app\models\ContentIndex;
use app\models\Content;
use app\models\CharacterBlock;
use app\models\Agent;
use app\models\ShareGood;
use app\models\ContentGood;
use app\models\User;


class IndexForm extends Model
{
    public $store_id;
    public $pingtai_id;
    public $user_id;

    public function search()
    {
        $pingtai = Store::findOne($this->pingtai_id);
        $store = Store::findOne($this->store_id);
        if (!$store)
            return [
                'code' => 1,
                'msg' => '平台不存在',
            ];
        $this->getMiaoshaData();
        $banner_list = Banner::find()->where([
            'is_delete' => 0,
            'store_id' => $this->pingtai_id,
            'type' => 1,
        ])->orderBy('sort ASC')->asArray()->all();
        foreach ($banner_list as $i => $banner) {
            $banner_list[$i]['open_type'] = 'navigate';
        }

        $nav_icon_list = HomeNav::find()->where([
            'is_delete' => 0,
            'store_id' => $this->pingtai_id,
        ])->orderBy('sort ASC,addtime DESC')->select('name,pic_url,url,name,open_type')->asArray()->all();

        $cat_list = Cat::find()->where([
            'is_delete' => 0,
            'parent_id' => 0,
            'store_id' => $this->pingtai_id,
        ])->orderBy('sort ASC')->asArray()->all();
        $count = Agent::find()->where(['store_id'=>$this->pingtai_id])->count();
        $ping_tai = Agent::find()->where(['store_id'=>$this->pingtai_id])->asArray()->all();
        if($count>0){
            $ping = AgentGood::find()->where(['store_id'=>$this->pingtai_id])->asArray()->one();
            $pingtai_id = $ping_tai['pingtai_id'];
            $good = $ping['good'];
        }else{
            $pingtai_id=0;
            $good='';
        }
//        echo $count;
//        var_dump($ping);
//        echo $ping['good'];
//        echo $good;
//        exit();
        foreach ($cat_list as $i => $cat) {
            $cat_list[$i]['page_url'] = '/pages/list/list?cat_id=' . $cat['id'];
            $cat_list[$i]['open_type'] = 'navigate';
            $cat_list[$i]['cat_pic'] = $cat['pic_url'];
            $goods_list_form = new GoodsListForm();
            $goods_list_form->store_id = $this->pingtai_id;
            $goods_list_form->cat_id = $cat['id'];
            $goods_list_form->limit = $store->cat_goods_count;
//            $goods_list_form->pingtai_id = $this->pingtai_id;
//            $goods_list_form->good = $good;
            $goods_list_form_res = $goods_list_form->search();
            $goods_list = $goods_list_form_res['code'] == 0 ? $goods_list_form_res['data']['list'] : [];
            $cat_list[$i]['goods_list'] = $goods_list;
        }

        $block_list = HomeBlock::find()->where(['store_id' => $this->pingtai_id, 'is_delete' => 0])->all();
        $new_block_list = [];
        foreach ($block_list as $item) {
            $new_block_list[] = [
                'id' => $item->id,
                'name' => $item->name,
                'data' => json_decode($item->data, true),
            ];
        }
        $user_id = \Yii::$app->user->identity->id;
        $coupon_form = new CouponListForm();
        $coupon_form->store_id = $this->pingtai_id;
        $coupon_form->user_id = $user_id;
        $coupon_list = $coupon_form->getList();

        $topic_list = Topic::find()->where(['store_id' => $this->pingtai_id, 'is_delete' => 0])->orderBy('sort ASC,addtime DESC')->limit(6)->select('id,title')->asArray()->all();
        return [
            'code' => 0,
            'msg' => 'success',
            'data' => [
                'module_list' => $this->getModuleList($pingtai),
                'store' => [
                    'id' => $store->id,
                    'name' => $store->name,
                    'is_coupon' => $pingtai->is_coupon,
                    'show_customer_service' => $pingtai->show_customer_service,
                    'service' => Option::get('service', $this->pingtai_id, 'admin', '/images/icon-service.png'),
                    'copyright' => $pingtai->copyright,
                    'copyright_pic_url' => $pingtai->copyright_pic_url,
                    'copyright_url' => $pingtai->copyright_url,
                    'contact_tel' => $pingtai->contact_tel,
                    'cat_style' => $pingtai->cat_style,
                    'address' => $pingtai->address,
                    'is_offline' => $pingtai->is_offline,
                ],
                'banner_list' => $banner_list,
                'nav_icon_list' => $nav_icon_list,
                'cat_goods_cols' => $pingtai->cat_goods_cols,
                'cat_list' => $cat_list,
                'block_list' => $new_block_list,
                'coupon_list' => $coupon_list,
                'topic_list' => $topic_list,
                'nav_count' => $pingtai->nav_count,
                'notice' => Option::get('notice', $this->pingtai_id, 'admin'),
                'miaosha' => $this->getMiaoshaData(),
                'pintuan' => $this->getPintuanData(),
                'content_topic'=>$this->getContentBlockList(),
                'good_topic'=>$this->getGoodBlockList(),
                'character'=>$this->getCharacterList(),
                'agent_good'=>$this->getAgentGood(),
            ],
        ];
    }

    private function getContentBlockList()
    {
        $list = ContentIndex::find()->where(['wechat_app_id'=>$this->pingtai_id,'is_delete'=>0])->asArray()->all();
        if(!empty($list)){
            $data=[];
            foreach($list as $key=>$value){
                $data = Content::find()->where(['subject_id'=>$value['id'],'is_delete'=>0])->asArray()->all();
                foreach($data as $k=> $value) {
                    $content_id = $value['id'];
//                    $res = Goods::find()->select('id as good_id,cover_pic as good_pic ,price as good_price,name as good_name,super_price,vip_price')->
//                    where(['in', 'id', $goods_id])->asArray()->all();
                    $res = ContentGood::find()->alias('cd')->leftJoin(['g'=>Goods::tableName()],'cd.goods_id=g.id')->select('g.name,g.price,g.super_price,g.vip_price,g.cover_pic,g.id')
                        ->where(['cd.content_id'=>$content_id,'cd.is_delete'=>0])->asArray()->all();
                    $data[$k]['goods']=$res;
                }
                $list[$key]['data']=$data;
            }
        }
        return $list;
    }
    private function getGoodBlockList(){
        $list = Cat::find()->select('id,home_url,home_title,home_title_s')->where(['store_id'=>$this->pingtai_id,'is_delete'=>0])->asArray()->all();
        if(!empty($list)){
            $data=[];
            foreach($list as $key=>$value){
                $data = Goods::find()->select('id as good_id,cover_pic,price,name,super_price,vip_price')->where(['store_id'=>$this->pingtai_id,'is_delete'=>0,'cat_id'=>$value['id']])->asArray()->all();
                $list[$key]['data']=$data;
            }
        }
        return $list;
    }
    private function getCharacterList(){
        $list = CharacterBlock::find()->where(['wechat_app_id'=>$this->pingtai_id,'is_delete'=>0])->asArray()->all();
        return $list;
    }

    /**
     * @param Store $store
     */
    private function getModuleList($store)
    {
        $list = json_decode($store->home_page_module, true);
        if (!$list) {
            $list = [
                [
                    'name' => 'banner',
                ],
                [
                    'name' => 'search',
                ],
                [
                    'name' => 'nav',
                ],
                [
                    'name' => 'topic',
                ],
                [
                    'name' => 'coupon',
                ],
                [
                    'name' => 'cat',
                ],
                [
                    'name'=>'content_topic',
                ],
            ];
        } else {
            $new_list = [];
            foreach ($list as $item) {
                if (stripos($item['name'], 'block-') !== false) {
                    $names = explode('-', $item['name']);
                    $new_list[] = [
                        'name' => $names[0],
                        'block_id' => $names[1],
                    ];
                } elseif (stripos($item['name'], 'single_cat-') !== false) {
                    $names = explode('-', $item['name']);
                    if($names[2]=='s'){
                        $new_list[] = [
                            'name'=>"goods_topic",
                            'cat_id'=>$names[1],
                        ];
                    }else {
                        $new_list[] = [
                            'name' => $names[0],
                            'cat_id' => $names[1],
                        ];
                    }
                } else {
                    $new_list[] = $item;
                }
            }
            $list = $new_list;
        }
        return $list;
    }

    public function getMiaoshaData()
    {
        $list = MiaoshaGoods::find()->alias('mg')
            ->select('g.id,g.name,g.cover_pic AS pic,g.price,mg.attr,mg.start_time')
            ->leftJoin(['g' => Goods::tableName()], 'mg.goods_id=g.id')
            ->where([
                'AND',
                [
                    'mg.is_delete' => 0,
                    'g.is_delete' => 0,
                    'mg.open_date' => date('Y-m-d'),
                    'g.status' => 1,
                    'mg.start_time' => date('H'),
                    'mg.store_id' => $this->pingtai_id,
                ],
            ])
            ->orderBy('g.sort ASC,g.addtime DESC')
            ->limit(10)
            ->asArray()->all();
        foreach ($list as $i => $item) {
            $item['attr'] = json_decode($item['attr'], true);
            $list[$i] = $item;
            $price_list = [];
            foreach ($item['attr'] as $attr) {
                if ($attr['miaosha_price'] <= 0) {
                    $price_list[] = doubleval($item['price']);
                } else {
                    $price_list[] = doubleval($attr['miaosha_price']);
                }
            }
            $list[$i]['price'] = number_format($list[$i]['price'], 2, '.', '');
            $list[$i]['miaosha_price'] = number_format(min($price_list), 2, '.', '');
            unset($list[$i]['attr']);
        }
        if (count($list) == 0)
            return [
                'name' => '暂无秒杀活动',
                'rest_time' => 0,
                'goods_list' => null,
            ];
        return [
            'name' => intval(date('H')) . '点场',
            'rest_time' => max(intval(strtotime(date('Y-m-d H:59:59')) - time()), 0),
            'goods_list' => $list,
        ];
    }

    public function getPintuanData()
    {
        $num_query = PtOrderDetail::find()->alias('pod')
            ->select('pod.goods_id,SUM(pod.num) AS sale_num')
            ->leftJoin(['po' => PtOrder::tableName()], 'pod.order_id=po.id')
            ->where([
                'AND',
                [
                    'pod.is_delete' => 0,
                    'po.is_delete' => 0,
                    'po.is_pay' => 1,
                ],
            ])->groupBy('pod.goods_id');
        $list = PtGoods::find()->alias('pg')
            ->select('pg.*,pod.sale_num')
            ->leftJoin(['pod' => $num_query], 'pg.id=pod.goods_id')
            ->where([
                'AND',
                [
                    'pg.is_delete' => 0,
                    'pg.status' => 1,
                    'pg.store_id' => $this->pingtai_id,
                ],
            ])->orderBy('pg.is_hot DESC,pg.sort ASC,pg.addtime DESC')
            ->limit(10)
            ->asArray()->all();
        $new_list = [];
        foreach ($list as $item) {
            $new_list[] = [
                'id' => $item['id'],
                'pic' => $item['cover_pic'],
                'name' => $item['name'],
                'price' => number_format($item['price'], 2, '.', ''),
                'sale_num' => intval($item['sale_num'] ? $item['sale_num'] : 0) + intval($item['virtual_sales'] ? $item['virtual_sales'] : 0),
            ];
        }
        return [
            'goods_list' => $new_list,
        ];
    }
    public function getLiveData()
    {
        $res_user = User::findOne(['id'=>$this->user_id]);

        $share = ShareGood::find()->select('good')->where(['store_id'=>$this->store_id])->asArray()->all();
        $share_good =explode(',',$share[0]['good']);
//        var_dump($share_good);
//        exit();
        //查詢平台id
        $pingtai_id=1;
        $query= Agent::find()->select('pingtai_id')->where(['store_id'=>$this->store_id])->asArray()->all();
//        var_dump($query);
        if(!empty($query)){
            $pingtai_id = $query[0]['pingtai_id'];
        }
        $room_data = LiveIndex::find()->where(['wechat_app_id'=>$this->store_id])->asArray()->all();
        $stream_data = LiveStream::find()->where(['wechat_app_id'=>$this->store_id])->asArray()->all();
        $list = Goods::find()->where(['store_id' => $pingtai_id, 'is_delete' => 0])->andWhere(['in','id',$share_good])->asArray()->all();
//        $list = Goods::find()->where(['store_id' => $this->store_id, 'is_delete' => 0,'is_live'=>1])->asArray()->all();
//        var_dump($list);
        foreach ($list as $key =>$value){
            if($res_user->is_vip==1){
                $list[$key]['price'] = $list[$key]['vip_price'];
            }else if($res_user->is_super ==1){
                $list[$key]['price'] = $list[$key]['super_price'];
            }
            $attr_rows = json_decode($value['attr'], true);
            if (empty($attr_rows))
                return [];
            $attr_group_list = [];
            foreach ($attr_rows as $attr_row) {
                foreach ($attr_row['attr_list'] as $i => $attr) {
                    $attr_id = $attr['attr_id'];
                    $attr = Attr::findOne(['id' => $attr_id, 'is_delete' => 0]);
                    if (!$attr)
                        continue;
                    $in_list = false;
                    foreach ($attr_group_list as $j => $attr_group) {
                        if ($attr_group->attr_group_id == $attr->attr_group_id) {
                            $attr_obj = (object)[
                                'attr_id' => $attr->id,
                                'attr_name' => $attr->attr_name,
                            ];
                            if (!in_array($attr_obj, $attr_group_list[$j]->attr_list)) {
                                $attr_group_list[$j]->attr_list[] = $attr_obj;
                            }
                            $in_list = true;
                            continue;
                        }
                    }
                    if (!$in_list) {
                        $attr_group = AttrGroup::findOne(['is_delete' => 0, 'id' => $attr->attr_group_id]);
                        if ($attr_group) {
                            $attr_group_list[] = (object)[
                                'attr_group_id' => $attr_group->id,
                                'attr_group_name' => $attr_group->attr_group_name,
                                'attr_list' => [
                                    (object)[
                                        'attr_id' => $attr->id,
                                        'attr_name' => $attr->attr_name,
                                    ],
                                ],
                            ];
                        }
                    }
                }
            }
            $list[$key]['group_attr_list'] = $attr_group_list;
            $list[$key]['nums'] = 1;
            $list[$key]['product_nums']=1;
        }
//var_dump($list);
        $data = array('roomName'=>$room_data[0]['room_name'],'roomId'=>$room_data[0]['roomid'],'pull_url'=>$stream_data[0]['pull_stream'],'avator'=>$room_data[0]['actor_imgurl']);

        return array('data'=>$data,'live_good'=>$list,'user_id'=>$this->user_id);
    }
    //获取内容专题
    public function getContentTopic(){

    }
    public function getAgentGood(){
        $query = AgentGood::find()->select('good')->where(['store_id'=>$this->store_id])->asArray()->all();
        if($query[0]['good']!=''){
            $good = explode(',',$query[0]['good']);
            $res = Goods::find()->where(['in','id',$good])->asArray()->all();
        }else{
            $res = '';
        }
        return $res;

    }
}